﻿using GalaSoft.MvvmLight.Messaging;
using JiveMessenger.Converters;
using JiveMessenger.Models;
using JiveMessenger.Utilities;
using JiveMessenger.ViewModels;
using JmShared;
using JmShared.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace JiveMessenger.CustomControls
{
    public sealed partial class ManageGroupControl : UserControl, INotifyPropertyChanged
    {
        //private double _groupMembersWidth;
        //public double GroupMembersWidth
        //{
        //    get { return _groupMembersWidth; }
        //    set
        //    {
        //        if (_groupMembersWidth != value)
        //        {
        //            _groupMembersWidth = value;
        //            RaisePropertyChanged("GroupMembersWidth");
        //        }
        //    }
        //}
        public ManageGroupControl()
        {
            this.InitializeComponent();
            //this.GroupMembersWidth = this.Width;
          //  this.DataContextPlaceholder.DataContext = this;
        }
        protected void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;

        private void ComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            IGroupMember member = cb.DataContext as IGroupMember;
            if (member != null)
            {
                //cb.ItemsSource = Enum.GetValues(typeof(GroupPrivilege));
                FillComboBox(cb, member);
                //  cb.SelectedValue = member.Privilege;
                cb.SelectedItem = member.Privilege.ToString();

            }
            else
            {

            }
        }

        //private void ListViewGroupMembers_SizeChanged(object sender, SizeChangedEventArgs e)
        //{
        //    GroupMembersWidth = e.NewSize.Width;
        //}

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (DesignMode.DesignModeEnabled)
                return;
            if (!(this.DataContext is ViewModelManageGroup))
                return;

        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = (ComboBox)sender;
            IGroupMember member = (IGroupMember)cb.DataContext;
            if (e.RemovedItems.Count == 0 || e.AddedItems.Count == 0)//this is true when we initially load the combobox items, so we just return;
                return;
            if (cb.Tag != null && (bool)cb.Tag == true)
            {
                cb.Tag = false;
                return;
            }
            GroupPrivilege newPrivilege = (GroupPrivilege)Enum.Parse(typeof(GroupPrivilege), e.AddedItems[0].ToString());


            Messenger.Default.Send(new NotificationMessageAction<bool>(this, new JiveDialogQuery("Change privilege?",string.Format("Change privilege for {0} from {1} to {2}?", member.Username, StaticMethods.GetEnumDescription(member.Privilege), newPrivilege)), "QueryDialog", async result =>
            {
                bool privilegeChanged = false;
                if (result == true)
                {
                    cb.IsEnabled = false;
                    //  member.Privilege = privilege;
                    MemberGroupPrivilege priv = new MemberGroupPrivilege(member.Username, Convert.ToInt32(((ViewModelManageGroup)this.DataContext).ChatGroup.ID), (GroupPrivilege)newPrivilege);
                    var response = await VmHelper.Locator.CurrentClient.Connection.SetGroupPrivilegeForUser(priv);
                    if (response.Success)
                    {
                        // member.Privilege =newPrivilege;
                        privilegeChanged = true;
                    }
                    else
                    {
                        //  cb.Tag = true;
                        // cb.SelectedItem = newPrivilege.ToString();

                        // cb.UpdateLayout();
                        Messenger.Default.Send(new JiveDialogMessage(response.StatusText));
                    }

                    cb.IsEnabled = true;

                }
                if (privilegeChanged)
                {
                    member.Privilege = newPrivilege;
                    cb.SelectedItem = newPrivilege.ToString();
                }
                else
                {
                    cb.Tag = true;
                    cb.SelectedItem = member.Privilege.ToString();
                    cb.UpdateLayout();
                }
            }));
        }

        private void ComboBox_DropDownOpened(object sender, object e)
        {
            ComboBox cb = (ComboBox)sender;
            IGroupMember member = (IGroupMember)cb.DataContext;
            //  foreach (GroupPrivilege item in cb.Items)
            for (int i = 0; i < cb.Items.Count; i++)
            {
                GroupPrivilege item = (GroupPrivilege)Enum.Parse(typeof(GroupPrivilege), cb.Items[i].ToString());
                bool include = false;
                if (member.Privilege == GroupPrivilege.Owner)
                    include = FilterOwnerPrivileges(item);
                else if (member.Privilege == GroupPrivilege.Moderator)
                    include = FilterModeratorPrivileges(item);
                else if (member.Privilege == GroupPrivilege.Member)
                    include = FilterMemberPrivileges(item);

                if (!include)
                    cb.Items.Remove(item.ToString());
            }
        }
        private void FillComboBox(ComboBox cb, IGroupMember member)
        {
            //var items = Enum.GetValues(typeof(GroupPrivilege)).Cast<GroupPrivilege>().Where(x=>
            //    {
            //        bool include = false;
            //        if (member.Privilege == GroupPrivilege.Owner)
            //            include = FilterOwnerPrivileges(x);
            //        else if (member.Privilege == GroupPrivilege.Moderator)
            //            include = FilterModeratorPrivileges(x);
            //        else if (member.Privilege == GroupPrivilege.Member)
            //            include = FilterMemberPrivileges(x);
            //        if (include)
            //            return true;

            //        return false;
            //    });

            //cb.ItemsSource = items;
            var items = Enum.GetValues(typeof(GroupPrivilege));
            cb.Items.Clear();
            foreach (var item in items)
            {
                bool include = false;
                if (member.Privilege == GroupPrivilege.Owner)
                    include = FilterOwnerPrivileges(item);
                else if (member.Privilege == GroupPrivilege.Moderator)
                    include = FilterModeratorPrivileges(item);
                else if (member.Privilege == GroupPrivilege.Member)
                    include = FilterMemberPrivileges(item);
                if (include)
                {
                    cb.Items.Add(item.ToString());
                }
            }
        }
        private bool FilterOwnerPrivileges(object p)
        {
            if (p is GroupPrivilege)
            {
                var privilege = (GroupPrivilege)p;
                var vm = (ViewModelManageGroup)this.DataContext;
                GroupPrivilege currentUserPrivilege = vm.GroupMembers.FirstOrDefault(x => x.Username == VmHelper.Locator.CurrentClient.CurrentUserInfo.UserName).Privilege;
                switch (currentUserPrivilege)
                {
                    case GroupPrivilege.Owner:
                        return privilege == GroupPrivilege.Owner;
                    case GroupPrivilege.Moderator:
                        return privilege == GroupPrivilege.Owner;
                    default:
                        return privilege == GroupPrivilege.Owner;
                }
            }
            else
                return false;
        }
        private bool FilterMemberPrivileges(object p)
        {
            if (p is GroupPrivilege)
            {
                var privilege = (GroupPrivilege)p;
                var vm = (ViewModelManageGroup)this.DataContext;
                GroupPrivilege currentUserPrivilege = vm.GroupMembers.FirstOrDefault(x => x.Username == VmHelper.Locator.CurrentClient.CurrentUserInfo.UserName).Privilege;
                switch (currentUserPrivilege)
                {
                    case GroupPrivilege.Owner:
                        return privilege == GroupPrivilege.Member || privilege == GroupPrivilege.Moderator;
                    case GroupPrivilege.Moderator:
                        return privilege == GroupPrivilege.Member;
                    default:
                        return privilege == GroupPrivilege.Member;
                }
            }
            else
                return false;
        }
        private bool FilterModeratorPrivileges(object p)
        {
            if (p is GroupPrivilege)
            {
                var privilege = (GroupPrivilege)p;
                var vm = (ViewModelManageGroup)this.DataContext;
                GroupPrivilege currentUserPrivilege = vm.GroupMembers.FirstOrDefault(x => x.Username == VmHelper.Locator.CurrentClient.CurrentUserInfo.UserName).Privilege;
                switch (currentUserPrivilege)
                {
                    case GroupPrivilege.Owner:
                        return privilege == GroupPrivilege.Member || privilege == GroupPrivilege.Moderator;
                    case GroupPrivilege.Moderator:
                        return privilege == GroupPrivilege.Member || privilege == GroupPrivilege.Moderator;
                    default:
                        return privilege == GroupPrivilege.Member || privilege == GroupPrivilege.Moderator;
                }

            }
            else
                return false;
        }

        private void UserControl_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
        {
            if (args.NewValue == null || !(args.NewValue is ViewModelManageGroup))
                return;
            var conv = this.Resources["ComboboxDisableConverter"] as ComboboxDisableConverter;
            if (conv != null)
            {
                conv.CurrentChatGroup = ((ViewModelManageGroup)this.DataContext).ChatGroup as JiveChatGroupModel;
                conv.CurrentUser = VmHelper.Locator.ViewModelContactList.CurrentUser;
            }
        }

    }
}
